package com.ygqh.baby.controller.mobile;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.ygqh.baby.ao.*;
import com.ygqh.baby.exception.YgException;
import com.ygqh.baby.handler.GroupBuyOrderCommitHandler;
import com.ygqh.baby.model.*;
import com.ygqh.baby.po.YgGroup;
import com.ygqh.baby.po.YgTuan;
import com.ygqh.baby.po.YgUser;
import com.ygqh.baby.service.*;
import com.ygqh.baby.utils.SessionUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 促销相关
 *
 * @author guohao
 */
@Controller
@RequestMapping("/app/grouporder")
public class YgGroupOrderController extends BaseController {
    @Autowired
    private YgOrderLogService ygOrderLogService;
    @Autowired
    private YgOrderService orderService;
    @Autowired
    private YgShoppingCarService shoppingCarService;
    @Autowired
    private YgGroupBuyingService ygGroupBuyingService;
    @Autowired
    private YgGroupService ygGroupService;
    @Autowired
    private YgSalesPromotionService ygSalesPromotionService;
    @Autowired
    private YgUserService ygUserService;
    @Autowired
    private YgTuanService ygTuanService;
    @Autowired
    private TrustoneService trustoneService;
    @Autowired
    private GroupBuyOrderCommitHandler groupBuyOrderCommitHandler;
    @Autowired
    private YgUserAuthsService ygUserAuthsService;

    /**
     * 商品详情页获取该分组下进行中的开团信息
     *
     * @param queryInfo 分页
     * @param groupId   分组id
     * @return
     */
    @RequestMapping(value = "findGroupBuyByGroupId")
    @ResponseBody
    public ResponseEntity findGroupByPid(QueryInfo queryInfo, Long groupId) {
        List<YgGroupBuyModel> models = ygGroupBuyingService.findGroupBuyByGroupId(queryInfo, groupId);
        Map<String, Object> map = new HashMap<>();
        YgGroup group = ygGroupService.findById(groupId);
        map.put("groupAmount", group.getGroupAmount());
        map.put("groupMode", group.getGroupMode());
        map.put("groupBuyList", models);
        return ResponseEntity.success(map);
    }

    /**
     * 获取某团信息
     *
     * @param groupBuyId 团id
     * @return
     */
    @RequestMapping(value = "findGroupBuyById")
    @ResponseBody
    public ResponseEntity findGroupBuyById(Long groupBuyId) {
        YgGroupBuyModel model = ygGroupBuyingService.findGroupBuyById(groupBuyId);
        return ResponseEntity.success(model);
    }

    /**
     * 获取拼团商品信息
     *
     * @param productId 商品id
     * @return
     */
    @RequestMapping(value = "findProductInfoWithGroup")
    @ResponseBody
    public ResponseEntity findProductInfoWithGroup(Long productId) {
        YgProductGroupModel model = ygGroupBuyingService.findProductInfoWithGroup(productId);
        return ResponseEntity.success(model);
    }

    /**
     * 获取其他拼团商品信息
     *
     * @param queryInfo 分页
     * @param productId 商品id
     * @return
     */
    @RequestMapping(value = "findOtherGroupProduct")
    @ResponseBody
    public ResponseEntity findOtherGroupProduct(QueryInfo queryInfo, Long productId) {
        List<YgProductGroupModel> model = ygGroupBuyingService.findOtherGroupProduct(queryInfo, productId);
        return ResponseEntity.success(model);
    }

    /**
     * 获取所有未完成的拼团
     *
     * @param queryInfo 分页
     * @return
     */
    @RequestMapping(value = "findAllGroupBuy")
    @ResponseBody
    public ResponseEntity findAllGroupBuy(QueryInfo queryInfo) {
        List<YgGroupBuyModel> model = ygGroupBuyingService.findAllGroupBuy(queryInfo);
        return ResponseEntity.success(model);

    }

    /**
     * 拼团结算页获取商品信息
     *
     * @param skuInfos 商品SKU信息
     * @return
     * @throws YgException
     */
    @RequestMapping(value = "findItemInfoPt")
    @ResponseBody
    public ResponseEntity findItemInfoPt(String skuInfos) throws YgException {
        Map<String, Object> map = new HashMap<>();
        YgUser user = SessionUtil.getCurrentUser();
        List<YgPtSkuInfo> skuList = JSON.parseObject(skuInfos, new TypeReference<List<YgPtSkuInfo>>() {
        });
        List<YgShoppingCarModel> list = shoppingCarService.findItemInfoPt(skuList, user.getId(), false,
                SALES_PLATFORM);
        StringBuilder sb = new StringBuilder();
        BigDecimal productPrice = new BigDecimal("0.00");
        BigDecimal specialPrice = new BigDecimal("0.00");
        BigDecimal vipPrice = new BigDecimal("0.00");
        BigDecimal totalPromotionPrice = new BigDecimal("0.00");
        for (YgShoppingCarModel model : list) {
            if (model.getPromotionPrice().compareTo(new BigDecimal("0")) == 0) {
                sb.append(model.getProductName()).append(",skuid=").append(model.getSkuId()).append(";");
            }
            productPrice = productPrice.add(model.getSalesPrice().multiply(new BigDecimal(model.getQuantity())));
            totalPromotionPrice = totalPromotionPrice.add(model.getRealSalesPrice()
                    .multiply(new BigDecimal(model.getQuantity())));

            if (PromotionType.IsSpecial.equals(model.getSalesType())) {
                specialPrice = specialPrice.add(model.getRealSalesPrice().multiply(new BigDecimal(model.getQuantity())));
            }
            BigDecimal vPrice = model.getVipPrice();
            if (vPrice == null || vPrice.compareTo(new BigDecimal("0.00")) == 0) {
                vPrice = model.getRealSalesPrice();
            }
            vipPrice = vipPrice.add(vPrice.multiply(new BigDecimal(model.getQuantity())));
        }
        if (sb.length() > 0) {
            sb.append("上述商品不是拼团商品");
            throw new YgException("-1", sb.toString());
        }
        List<List<YgShoppingCarModel>> sortCarList = shoppingCarService.sortCarList(list, user.getId());
        map.put("carList", sortCarList);
        map.put("productPrice", productPrice);
        map.put("specialPrice", totalPromotionPrice);
        map.put("vipDisPrice", totalPromotionPrice.subtract(vipPrice));
        map.put("trustoneFlag", trustoneService.validateIsTrustonerOrder(list));
        return ResponseEntity.success(map);
    }

    @SuppressWarnings("unchecked")
    @RequestMapping(value = "commitOrderPt")
    @ResponseBody
    public ResponseEntity commitOrderPt(String skuInfos, Long groupId, Long groupBuyId, Long userAddressId,
                                        Long couponDetailId, AppType appType, PayType payType, BigDecimal totalPrice,
                                        String sourceCode, BigDecimal accountPrice, String userRemark,
                                        String platformNo, String identityNo, String formId, String linkCode,
                                        HttpServletRequest request)
            throws YgException {
        if (PayType.Small.equals(payType)) {
            payType = PayType.WeChat;
        }
        YgUser user = SessionUtil.getCurrentUser();
        String openid = ygUserAuthsService.getOpenId(user.getId(), PLATFORM_NO, appType);
        Message msg;
        List<YgPtSkuInfo> skuList = JSON.parseObject(skuInfos, new TypeReference<List<YgPtSkuInfo>>() {
        });
        Boolean isNew = ygUserService.isNewCustom(user.getId(), PLATFORM_NO);
        msg = ygGroupBuyingService.checkNewCustomGroup(skuList, isNew, accountPrice);
        if (msg.getType().equals(Message.Type.error)) {
            return ResponseEntity.converter(msg);
        }

        if (StringUtils.isBlank(platformNo)) {
            platformNo = PLATFORM_NO;
        }
        ygOrderLogService.addOrderLog(user.getId(), OrderStatus.WaitingPay, user.getUserName(),
                "提交订单,【入参】：skuInfos=" + skuInfos + ";" +
                        "groupId=" + groupId + ";" +
                        "groupBuyId=" + groupBuyId + ";" +
                        "userAddressId=" + userAddressId + ";" +
                        "couponDetailId=" + couponDetailId + ";" +
                        "appType=" + appType + ";" +
                        "payType=" + payType + ";" +
                        "totalPrice=" + totalPrice + ";" +
                        "sourceCode" + sourceCode
                        + ";accountPrice=" + accountPrice + ";" +
                        "userRemark=" + userRemark + ";" +
                        "platformNo=" + platformNo + ";" +
                        "identityNo=" + identityNo);

        // 校验核销
        msg = ygSalesPromotionService.checkHeXiao(skuList, user.getId());
        if (msg.getType().equals(Message.Type.error)) {
            return ResponseEntity.converter(msg);
        }
        OrderType orderType = OrderType.GroupBuying;
        if ((Boolean) msg.getExtra()) {
            orderType = OrderType.HeXiao;
        }

        // 卡券订单
        if (request.getAttribute("sourceOrderType") != null
                && request.getAttribute("sourceOrderType").toString().endsWith(OrderType.CardCoupon.name())) {
            orderType = OrderType.CardCoupon;
        } else {
            YgGroup group = ygGroupService.findById(groupId);
            // 老带新 只限新用户参团，老用户只能发起拼团
            if (GroupMode.OldBeltNew.equals(group.getGroupMode())) {
                if (groupBuyId != null && groupBuyId != 0 && !isNew) {
                    return ResponseEntity.error("亲，该拼团只限新用户参团。", groupBuyId + "-" + isNew);
                }
                Long quantity = skuList.get(0).getQuantity();
                if (skuList.size() > 1 || quantity > 1) {
                    return ResponseEntity.error("亲，该拼团限一件。", groupBuyId + "-" + isNew);
                }

            } else if (GroupMode.OnlyNew.equals(group.getGroupMode()) && !isNew) {
                return ResponseEntity.error("亲，该拼团只限新用户。", groupBuyId + "-" + isNew);
            }
        }

        // 保存订单
        GroupOrderCommitParam commitParam = new GroupOrderCommitParam(skuList, user.getId(), user.getUserName(),
                userAddressId, couponDetailId, totalPrice, appType, payType, sourceCode, accountPrice, formId, groupId,
                groupBuyId, orderType, userRemark, platformNo, identityNo, SALES_PLATFORM, false);
        msg = groupBuyOrderCommitHandler.commitOrder(commitParam);
        // 订单保存成功
        if (msg.getType().equals(Message.Type.success)) {
            Map<String, Object> map = (Map<String, Object>) msg.getExtra();
            map.put("openid", openid);
            map.put("totalPrice", totalPrice.subtract(accountPrice));
            msg.setExtra(map);
            msg.setContent("订单提交成功");
            ygOrderLogService.addOrderLog((Long) map.get("orderId"), OrderStatus.WaitingPay, user.getUserName(), "订单提交成功：" + map.toString());
        } else {
            logger.info(
                    "订单提交失败，msgType:" + msg.getType() + ";msg:" + msg.getContent() + ";msgExtra:" + (msg.getExtra() == null ? "" : msg.getExtra().toString()));
        }
        return ResponseEntity.converter(msg);
    }

    /**
     * @param queryInfo 分页
     * @param userName  用户名
     * @return JSONPObject 返回类型
     * @throws @date 2017年7月5日 下午12:07:41
     * @Title: findOrderListByHeXiao
     * @Description: 获取核销列表页
     * @author （guohao）
     * @version V1.0
     */
    @RequestMapping(value = "findOrderListByHeXiao")
    @ResponseBody
    public ResponseEntity findOrderListByHeXiao(QueryInfo queryInfo, String userName) {
        List<YgOrderModel> orderList = orderService.findOrderListByHeXiao(queryInfo, OrderStatus.WaitingSend, userName);
        return ResponseEntity.success(orderList);
    }

    /**
     * 拼团Banner列
     *
     * @param queryInfo 分页
     * @param groupMode 拼团模式
     * @param attribute 拼团属性
     * @return
     */
    @RequestMapping(value = "findTuanData")
    @ResponseBody
    public ResponseEntity findTuanData(QueryInfo queryInfo,
                                       @RequestParam(defaultValue = "Ordinary") GroupMode groupMode, String attribute) {
        Map<String, Object> data = new HashMap<>();
        List<YgTuan> currentTuanList = ygTuanService.
                findList(queryInfo, PromotionStatus.Running, null, null, groupMode, attribute);
        List<YgTuan> futureTuanList = ygTuanService.
                findList(queryInfo, PromotionStatus.NotStarted, null, null, groupMode, attribute);
        data.put("currentTuanList", currentTuanList);
        data.put("futureTuanList", futureTuanList);
        data.put("currentTimeZone", System.currentTimeMillis());
        return ResponseEntity.success(data);
    }

    @RequestMapping(value = "findTuanMemberList", method = RequestMethod.GET)
    @ResponseBody
    public ResponseEntity findTuanMemberList(Long groupBuyId) {
        List<Map<String, Object>> list = ygGroupBuyingService.findTuanMemberList(groupBuyId);
        return ResponseEntity.success(list);
    }

    @RequestMapping(value = "findTuanAttribute", method = RequestMethod.GET)
    @ResponseBody
    public ResponseEntity findTuanAttribute() {
        return ResponseEntity.success(ygTuanService.findTuanAttribute());
    }

}
